package com.zahb.qadx.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;

import com.google.gson.Gson;
import com.luozm.captcha.Captcha;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.view.captcha.CaptchaDialog;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.EditTextHelper;
import com.zahb.qadx.util.InputMethodUtil;
import com.zahb.qadx.util.RegularUtil;
import com.zahb.qadx.util.SimpleTextWatcher;
import com.zahb.qadx.util.SmsCodeViewWrapper;
import com.zahb.qadx.util.Tips;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by huwei.
 * Data 2020-10-13.
 * Time 11:26.
 */
public class ReplacePhone extends BaseActivity {
    @BindView(R.id.et_phone)
    AppCompatEditText etPhone;
    @BindView(R.id.tv_get_auth_code)
    TextView tvGetAuthCode;
    @BindView(R.id.et_auth_code)
    EditText etAuthCode;
    @BindView(R.id.layout_sms_code_view)
    RelativeLayout layoutSmsCodeView;
    @BindView(R.id.btn_login)
    AppCompatButton btnLogin;
    private SmsCodeViewWrapper mSmsCodeViewWrapper;
    private Gson mGson = new Gson();

    @Override
    protected int getLayout() {
        return R.layout.activity_replace_phone;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        mTopBarContainer.setVisibility(View.VISIBLE);
        etPhone.setText(getIntent().getStringExtra("phone"));
        EditTextHelper.getEditTextDeleteIconWrapper(etPhone).setTextWatcher(mSimpleTextWatcher);
        mSmsCodeViewWrapper = new SmsCodeViewWrapper(layoutSmsCodeView);
        mSmsCodeViewWrapper.setOnGetSmsCodeViewClickListener(view -> {
            InputMethodUtil.hideInputMethod(getActivity());
            getSmsCodeCheck();
            //getSmsCode();
        });
        mSmsCodeViewWrapper.setTextWatcher(mSimpleTextWatcher);
    }

    private SimpleTextWatcher mSimpleTextWatcher = new SimpleTextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            btnLogin.setEnabled(!CompatHelper.isEmpty(etPhone) && !TextUtils.isEmpty(mSmsCodeViewWrapper.getSmsCode()));
        }
    };

    @Override
    protected int getTitleStringRes() {
        return R.string.replace_phone;
    }

    private void showCaptchaDialog() {
        CaptchaDialog.showCaptchaDialog(getContext(), new Captcha.CaptchaListener() {
            @Override
            public String onAccess(long time) {
                getSmsCode();
                return null;
            }

            @Override
            public String onFailed(int failCount) {
                return null;
            }

            @Override
            public String onMaxFailed() {
                return null;
            }
        });
    }

    private void getSmsCodeCheck() {
        String phone = CompatHelper.getString(etPhone);
        if (!RegularUtil.isValidMobileNumber(phone)) {
            showBindToast("手机号格式错误");
        } else {
            showCaptchaDialog();
        }
    }

    // 获取验证码
    private void getSmsCode() {

        mSmsCodeViewWrapper.startCountDown();

        Map<String, Object> params = new HashMap<>();
        params.put("mouldCode", "SMS_26775007");
        params.put("needCheck", 1);
        params.put("phone", CompatHelper.getString(etPhone));
        params.put("type", 1);

        String json = mGson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        addDisposable(RetrofitService.getNetService()
                .sendSmsCode(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == 200) {
                        showBindToast("验证码发送成功");
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                    mSmsCodeViewWrapper.stopCountDown();
                }));
    }

    // 判断验证码是否正确
    private void verifySmsCode() {
        String phone = CompatHelper.getString(etPhone);
        String smsCode = mSmsCodeViewWrapper.getSmsCode();
        if (!RegularUtil.isValidMobileNumber(phone)) {
            showBindToast("手机号格式错误");
            return;
        }
        if (!RegularUtil.isValidSmsCode(smsCode)) {
            showBindToast("验证码错误或已过期");
            return;
        }
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .verifySmsCode(phone, smsCode, 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getStatusCode() == 200) {
                        showBindToast("验证成功");
                        Intent intent = new Intent(ReplacePhone.this,ReplaceNewPhone.class);
                        intent.putExtra("phone",phone);
                        startActivity(intent);
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    Tips.RequestError(getActivity());
                }));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.btn_login)
    public void onViewClicked() {
        InputMethodUtil.hideInputMethod(getActivity());
        verifySmsCode();
    }
}
